<template>
    <LayoutWrap class="expenditure">
        <el-form :inline="true" :model="formSearch" ref="ruleForm" class="demo-form-inline">
            <el-form-item prop="toName" label="收入名称">
                <el-input
                    v-model="formSearch.toName"
                    placeholder="请输入收入名称"
                    :style="{width: formInputWidth}"
                    clearable
                    @keyup.enter.native="handleSearch"
                ></el-input>
            </el-form-item>
            <el-form-item prop="daterange" label="开始时间">
                <TheElDatePicker
                    type="datetime"
                    v-model="formSearch.daterange[0]"
                    @keyup.enter.native="handleSearch"
                    placeholder="请选择收入开始时间"
                    :style="{width: formInputWidth}"
                ></TheElDatePicker>
            </el-form-item>
            <el-form-item prop="datetime" label="结束时间">
                <TheElDatePicker
                    type="datetime"
                    v-model="formSearch.daterange[1]"
                    @keyup.enter.native="handleSearch"
                    placeholder="请选择收入结束时间"
                    :style="{width: formInputWidth}"
                ></TheElDatePicker>
            </el-form-item>
            <el-form-item>
                <el-button type="default" @click="$refs['ruleForm'].resetFields()">重置</el-button>
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
        </el-form>
        <ul class="list-head">
            <li v-if="isOperation" class="list-head-item">
                <el-button class="margin-left:auto;" @click="handleAdd" type="primary">创建收入订单</el-button>
            </li>
        </ul>
        <ul class="list-head">
            <li v-if="!isMobile" class="list-head-item">
                <CheckedColumns
                    :checkedId="checkedId"
                    :dataSource="checkedOpts"
                    v-model="checkedValues"
                ></CheckedColumns>
            </li>
            <!-- 其他统计 -->
            <li v-if="isMobile" class="list-head-item">
                <CheckedColumns
                    :checkedId="checkedId"
                    :dataSource="checkedOpts"
                    v-model="checkedValues"
                ></CheckedColumns>
            </li>
        </ul>
        <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column
                v-if="checkedValues.includes('toName')"
                prop="toName"
                key="toName"
                label="收入名称"
                sortable
            ></el-table-column>
            <el-table-column
                v-if="checkedValues.includes('toMoney')"
                prop="toMoney"
                key="toMoney"
                label="收款金额"
                sortable
                :sort-method="handleSortMoney"
            >
                <template v-slot="{row}">{{ row.toMoney | keep2decimalPlaces }}</template>
            </el-table-column>
            <el-table-column
                v-if="checkedValues.includes('toStatus')"
                prop="toStatus"
                key="toStatus"
                label="收款状态"
                sortable
            ></el-table-column>
            <el-table-column
                v-if="checkedValues.includes('toTime')"
                prop="toTime"
                key="toTime"
                label="收款时间"
                sortable
            ></el-table-column>
            <!-- 收款到账时间 -->
            <el-table-column
                v-if="checkedValues.includes('fromTime')"
                prop="fromTime"
                label="到账时间"
                sortable
            ></el-table-column>
            <el-table-column
                v-if="checkedValues.includes('toMode')"
                prop="toMode"
                key="toMode"
                label="收款方式"
                sortable
            ></el-table-column>
            <el-table-column
                v-if="checkedValues.includes('toAccount')"
                prop="toAccount"
                label="收款账号"
                sortable
            ></el-table-column>
            <el-table-column
                v-if="checkedValues.includes('toType')"
                prop="toType"
                key="toType"
                label="收入类型"
                sortable
            ></el-table-column>
            <el-table-column
                v-if="checkedValues.includes('fromAccount')"
                prop="fromAccount"
                key="fromAccount"
                label="付款账号"
                sortable
            ></el-table-column>
            <el-table-column
                v-if="checkedValues.includes('toRemark')"
                prop="toRemark"
                key="toRemark"
                label="备注"
                sortable
            ></el-table-column>

            <el-table-column v-if="checkedValues.includes('operation')" key="operation" align="center" label="操作">
                <template v-slot="{row}">
                    <el-button @click="handleDetail(row)" type="text">查看</el-button>
                    <template v-if="isOperation">
                        <el-button @click="handleEdit(row)" type="text">编辑</el-button>
                        <el-button @click="handleShowDeleteDialog(row)" type="text">删除</el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>
        <Pagination
            :page-size.sync="formSearch.pageSize"
            :page.sync="formSearch.page"
            :total="formSearch.count"
            @change="onChangePage"
        />
        <RevenueDialog
            v-if="isOperation"
            title="创建收入订单"
            :data-source="dataSourceAdd"
            :visible.sync="revenueDialogVisible"
            @on-ok="getList"
        ></RevenueDialog>
        <RevenueDialog
            title="查看收入订单"
            :data-source="dataSourceDetail"
            :visible.sync="revenueDialogVisibleDetail"
        ></RevenueDialog>
        <RevenueDialog
            v-if="isOperation"
            title="编辑收入订单"
            :data-source="dataSourceEdit"
            :visible.sync="revenueDialogVisibleEdit"
            @on-ok="getList"
        ></RevenueDialog>
        <TheElDialog v-if="isOperation" title="删除收入订单" :visible.sync="revenueDialogVisibleDelete">
            <span>你确定删除 {{ currentRow.toName }}？</span>
            <span slot="footer" class="dialog-footer">
                <el-button :loading="dialogLoading" @click="revenueDialogVisibleDelete = false">取 消</el-button>
                <el-button :loading="dialogLoading" type="primary" @click="handleDelete(currentRow)">确 定</el-button>
            </span>
        </TheElDialog>
    </LayoutWrap>
</template>

<script>
import {formInputWidth} from '@/styles/variables.scss';
import RevenueDialog from './RevenueDialog';
import {mixinIsOperation} from '@/mixins';
import {getRevenueList, getRevenueById, deleteRevenueById} from '@/api/revenue';
import moment from 'moment';
import {
    BASIC_MONEY,
    getRevenueModeMap,
    getRevenueStatusMap,
    getPickerOptions,
    THE_MOMENT_YYMMDD_HHMMSS,
    THE_MOMENT_YYYYMMDD_HHMMSS
} from '@/utils/constant';
import {keep2decimalPlaces} from '@/filters';
import CheckedColumns from '@/components/CheckedColumns';
import {THE_CHECKED_REVENUE} from '@/utils/list-types';
import {mapGetters} from 'vuex';
function getDefaultItem(params) {
    const defaultItem = {
        toName: '',
        toMoney: '',
        toTime: '',
        fromTime: '',
        toMode: [],
        toAccount: '',
        toStatus: '',
        toType: '',
        fromAccount: '',
        toRemark: ''
    };
    return defaultItem;
}
function handleGetColumns() {
    const column = {
        toName: '收入名称',
        toMoney: '收款金额',
        toStatus: '收款状态',
        toTime: '收款时间',
        fromTime: '到账时间',
        toMode: '收款方式',
        toAccount: '收款账号',
        toType: '收入类型',
        fromAccount: '付款账号',
        toRemark: '备注',
        operation: '操作'
    };
    return Object.keys(column).map(item => ({label: column[item], value: item}));
}

export default {
    name: 'revenue',
    components: {
        RevenueDialog,
        CheckedColumns
    },
    mixins: [mixinIsOperation],
    data() {
        return {
            formInputWidth,
            pickerOptions: getPickerOptions(),
            formSearch: {
                daterange: [],
                toName: '',
                count: 0, // 总条数
                pageSize: 10, // 一页多少条
                page: 1 // 当前第几页
            },
            // 新建弹窗
            revenueDialogVisible: false,
            // 编辑
            revenueDialogVisibleEdit: false,
            // 查看详情
            revenueDialogVisibleDetail: false,
            // 删除
            revenueDialogVisibleDelete: false,
            // 操作
            currentRow: {},
            // 删除loading
            dialogLoading: false,
            // 添加
            dataSourceAdd: getDefaultItem(),
            dataSourceDetail: getDefaultItem(),
            dataSourceEdit: getDefaultItem(),
            tableData: [],
            checkedValues: ['toName', 'toMoney', 'toTime', 'operation'], // 默认选中的数据
            checkedOpts: handleGetColumns(), // 需要选择的数据[{}, {label: '', value: ''}]
            checkedId: THE_CHECKED_REVENUE
        };
    },
    computed: {
        ...mapGetters({
            isMobile: 'app/isMobile'
        })
    },
    watch: {
        'formSearch.daterange': {
            handler(val) {
                if (!val) {
                    this.formSearch.daterange = [];
                }
            },
            deep: true
        }
    },
    created() {
        this.handleSearch();
    },
    methods: {
        onChangePage(value) {
            this.formSearch = {...this.formSearch, ...value};
            this.getList();
        },
        handleSelectionChange() {},
        handleSortMoney(a, b) {
            return b.toMoney - a.toMoney;
        },
        // 查询数据
        handleSearch() {
            this.getList();
        },
        // 获取 收入列表
        async getList() {
            const formSearch = this.formSearch;
            let [startTime, endTime] = formSearch.daterange;
            startTime = startTime || undefined;
            endTime = endTime || undefined;

            const newItem = {
                startTime,
                endTime,
                toName: (formSearch.toName || '').trim(),
                page: formSearch.page,
                pageSize: formSearch.pageSize
            };
            try {
                const result = await getRevenueList(newItem);
                const {data = [], status, page, pageSize, count} = result.data;

                if (status === 200) {
                    const revenueModeMap = getRevenueModeMap();
                    const revenueStatusMap = getRevenueStatusMap();

                    const tableData = data.map(item => {
                        const toMode = item.toMode
                            .split(',')
                            .map(mid => revenueModeMap[mid])
                            .join(',');
                        const toStatus = revenueStatusMap[item.toStatus];

                        return {
                            ...item,
                            toMoney: keep2decimalPlaces(item.toMoney / BASIC_MONEY),
                            toMode,
                            toStatus,
                            toTime: moment(item.toTime).format(THE_MOMENT_YYMMDD_HHMMSS),
                            fromTime: moment(item.toTime).format(THE_MOMENT_YYMMDD_HHMMSS)
                        };
                    });
                    this.tableData = tableData;
                    this.formSearch = {...formSearch, page, pageSize, count};
                }

                return result;
            } catch (error) {
                return error;
            }
        },
        // 创建、添加订单
        handleAdd() {
            this.revenueDialogVisible = true;
        },
        // 编辑
        async handleEdit(row) {
            this.revenueDialogVisibleEdit = true;
            try {
                this.dataSourceEdit = await this.handleGetItemData(row._id);
            } catch (error) {
                this.dataSourceEdit = {...getDefaultItem()};
            }
        },
        // 详情
        async handleDetail(row) {
            this.revenueDialogVisibleDetail = true;
            try {
                this.dataSourceDetail = await this.handleGetItemData(row._id);
            } catch (error) {
                this.dataSourceDetail = {...getDefaultItem()};
            }
        },

        async handleDelete(row) {
            this.dialogLoading = true;
            try {
                const result = await deleteRevenueById(row._id);
                const {status} = result.data;
                if (status === 204) {
                    this.$message({showClose: true, type: 'success', message: '删除成功'});
                    this.getList();
                } else {
                    throw result;
                }
            } catch (error) {
                this.$message({showClose: true, type: 'error', message: '删除失败'});
            }
            this.revenueDialogVisibleDelete = false;
            this.dialogLoading = false;
        },
        async handleGetItemData(id) {
            const defaultItem = getDefaultItem();
            try {
                const result = await getRevenueById(id);
                const {status, data = defaultItem} = result.data;
                if (status === 200) {
                    return {
                        ...data,
                        toMoney: keep2decimalPlaces(data.toMoney / BASIC_MONEY),
                        toMode: data.toMode.split(','),
                        toTime: moment(data.toTime).format(THE_MOMENT_YYYYMMDD_HHMMSS),
                        fromTime: moment(data.fromTime).format(THE_MOMENT_YYYYMMDD_HHMMSS)
                    };
                } else {
                    throw result;
                }
            } catch (error) {
                return error;
            }
        },

        // 弹出删除弹窗
        handleShowDeleteDialog(row) {
            // 展示删除弹窗
            this.revenueDialogVisibleDelete = true;
            this.currentRow = row;
        }
    }
};
</script>
